package net.example.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.oraycn.esbasic.helpers.FileHelper;
import com.oraycn.esbasic.helpers.StringHelper;
import com.oraycn.esbasic.models.FileType;
//import com.oraycn.esbasic.views.PhotoView;
import com.oraycn.esbasic.views.photoView.PhotoView;
import com.oraycn.esframework.common.TransferingProject;
import com.oraycn.esframeworkboost.networkdisk.Comment4NDisk;
import com.oraycn.esframeworkboost.networkdisk.FileDetail;
import com.oraycn.esframeworkboost.networkdisk.NDiskParameters;
import com.oraycn.esframeworkboost.networkdisk.SharedDirectory;
import com.zyao89.view.zloading.ZLoadingDialog;
import com.zyao89.view.zloading.Z_TYPE;

import net.example.activity.adapter.FileInfoAdapter;
import net.example.manager.Manager;
import net.example.manager.GGApplication;
import net.example.model.FileTransferUseType;
import net.example.model.event.FileEvent;
import net.example.ggtalk.R;
import net.example.utils.ConfigUtils;
import net.example.utils.ToastUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import Utils.FileTransferStatus;
import de.greenrobot.event.EventBus;


public class GroupFileActivity extends Activity implements ListView.OnItemClickListener {

    private FileInfoAdapter adapter;
    private List<FileDetail> fileDetailList=new ArrayList<>();
    private ListView listView;
    private TextView tv_content;
    private PhotoView photoView;
    private String netDiskID;
    private String ownerID ="_0";
    private boolean lockRootDirectory =true;// 锁定为只访问根目录
    private Handler mhandler ;
    private String currentDirPath;
    ZLoadingDialog dialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_group_file);
        mhandler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what)
                {
                    case FileInfoAdapter.DataSetChangeCompleted:
                        dialog.cancel();
                        break;
                }
            }
        };
        String groupID=getIntent().getStringExtra("groupID");
        this.netDiskID= "GroupShare_" + groupID.substring(1);
        this.currentDirPath= lockRootDirectory?netDiskID:null;
        this.initViews();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        new Thread(){
            @Override
            public void run() {
                mhandler.post(new Runnable() {
                    @Override
                    public void run() {
                        SharedDirectory sharedDirectory= Manager.getInstance().getNDiskOutter().GetSharedDirectory(ownerID,netDiskID,currentDirPath);
                        if(sharedDirectory!=null)
                        {
                            initFileDetailList(sharedDirectory.FileList);
                            String filesContent=String.format("共%d个文件（占用%s）",sharedDirectory.FileList.size(), FileHelper.getFileLengthString(sharedDirectory.getTotalFileSize()));
                            tv_content.setText(filesContent);
                        }
                        List<String> projectIDs= GGApplication.getInstance().getEngine().getFileOutter().getTransferingAbout(ownerID);
                        setBeforeProcssing(projectIDs);
                    }
                });
            }
        }.start();

    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    private void initViews()
    {
        dialog= new ZLoadingDialog(GroupFileActivity.this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            dialog.setLoadingBuilder( Z_TYPE.CIRCLE)//设置类型
                    .setLoadingColor(getColor(R.color.red) )//颜色
                    .setHintText("数据加载中...")
                    .setHintTextSize(16) // 设置字体大小 dp
                    .setHintTextColor(getColor(R.color.gray))  // 设置字体颜色
                    .setDurationTime(0.5) // 设置动画时间百分比 - 0.5倍
                    .setDialogBackgroundColor(getColor(R.color.white))
//                    .create()
                    .show(); // 设置背景色，默认白色

        }
        ((ImageView) findViewById(R.id.ct_photo)).setVisibility(View.GONE);
        TextView tv_title=(TextView)findViewById(R.id.headerText) ;
        tv_title.setText("群文件");
        this.tv_content=(TextView)findViewById(R.id.tv_content);
        //this.imgContainer=(ViewGroup)findViewById(R.id.img_container);
        this.photoView=(PhotoView)findViewById(R.id.photo_view);
//        zoomImageListener=new ZoomImageListener(this);
//        zoomImageListener.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                imgContainer.setVisibility(View.GONE);
//                findViewById(R.id.group1).setVisibility(View.VISIBLE);
//            }
//        });
//        zoomImageListener.setImageView(photoView);
        //photoView.setOnTouchListener(zoomImageListener);

        this.photoView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                photoView.setVisibility(View.GONE);
                findViewById(R.id.group1).setVisibility(View.VISIBLE);
            }
        });
        listView=(ListView)findViewById(R.id.lv_fileList);
        listView.setOnItemClickListener(this);
        adapter = new FileInfoAdapter(this,this.fileDetailList,R.layout.file_info_item);
        adapter.setListView(listView);
        adapter.setHandler(mhandler);
        listView.setAdapter(adapter);
    }

    private void initFileDetailList(List<FileDetail> details)
    {
        String saveDirPath=ConfigUtils.SDFileSavePath + currentDirPath+ "/";
        List<String> fileNames= FileHelper.getAllFileNames(saveDirPath);
        for (FileDetail fileDetail : details)
        {
            if(fileNames.contains(fileDetail.Name))
            {
                fileDetail.SavePath = saveDirPath + fileDetail.Name;
                fileDetail.Status = FileTransferStatus.Completed;
            }
        }
        this.fileDetailList.clear();
        this.fileDetailList.addAll(details);
        this.adapter.notifyDataSetChanged();
    }


    /**
     * 设置之前进入页面之前后台传输的进度
     * @param projectIDs
     */
    private void setBeforeProcssing(List<String> projectIDs)
    {
        if(projectIDs==null||projectIDs.size()==0){return;}
        for (String projectID:projectIDs)
        {
            TransferingProject project = GGApplication.getInstance().getEngine().getFileOutter().getTransferingProject(projectID);
            if(project==null||project.isFinish()){return;}
            NDiskParameters nDiskParameters= Comment4NDisk.Parse(project.getComment());
            if(nDiskParameters==null) {return;}
            if(!nDiskParameters.NetDiskID.equals(this.netDiskID)){return;}
            for (FileDetail fileDetail:this.fileDetailList)
            {
                if(fileDetail.Name.equals(project.getFileName()))
                {
                    fileDetail.ProjectId=projectID;
                    fileDetail.Status = FileTransferStatus.Transfering;
                }
            }
        }
        this.adapter.notifyDataSetChanged();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        FileDetail fileDetail=this.fileDetailList.get(position);
        if(fileDetail.Status==FileTransferStatus.Transfering)
        {
            this.showCancelDialog(fileDetail);
            return;
        }
        else  if(fileDetail.Status==FileTransferStatus.Completed)
        {
            if(this.autoOpenFile(fileDetail))
            {
                return;
            }
            FileHelper.openFile(this,new File(fileDetail.SavePath));
            return;
        }else if(fileDetail.Status==FileTransferStatus.Cancelled)
        {

        }
        final String sourceRemotePath=this.currentDirPath + "\\"+ fileDetail.Name;
        final String savePath=ConfigUtils.SDFileSavePath + this.currentDirPath + "/" + fileDetail.Name;
        fileDetail.SavePath=savePath;
        new Thread(){
            @Override
            public void run() {
                super.run();
                Manager.getInstance().getNDiskOutter().Download(ownerID,netDiskID, sourceRemotePath,savePath ,true);
            }
        }.start();

    }

    //弹出提示框
    private void showCancelDialog(final FileDetail fileDetail) {
        /* @setIcon 设置对话框图标
         * @setTitle 设置对话框标题
         * @setMessage 设置对话框消息提示
         * setXXX方法返回Dialog对象，因此可以链式设置属性
         */
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(GroupFileActivity.this);
        normalDialog.setTitle("提示");
        normalDialog.setMessage(String.format("您确定要取消%s传输吗？", fileDetail.Name));
        normalDialog.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                    }
                });
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        GGApplication.getInstance().getEngine().getFileOutter().cancelTransfering(fileDetail.ProjectId);
                    }
                });

        // 显示
        normalDialog.show();
    }

    public void onEventMainThread(FileEvent event)
    {
        try {
            if(event==null||event.FileTransferUseType!= FileTransferUseType.Comment4NDisk||event.TransferingProject==null){return;}
            TransferingProject project =event.TransferingProject;
            //对方是服务器
            if((project.getDestUserID().equals(this.ownerID)))
            {
                int pos = this.getFileDetailPos(event.ProjectId);
                switch (event.Type)
                {
                    case FileEvent.FILE_START:
                        NDiskParameters nDiskParameters= Comment4NDisk.Parse(project.getComment());
                        for (FileDetail detail : fileDetailList)
                        {
                            if(detail.SavePath.equals(nDiskParameters.DirectoryPath))
                            {
                                detail.ProjectId = project.getProjectId();
                                detail.Status= FileTransferStatus.Transfering;
                                event.FileSize=project.getFileSize();
                                event.TransferSize=0;
                                adapter.fileProcess(event);
                                break;
                            }
                        }
                        break;
                    case FileEvent.FILE_COMPLETED:
                        if(pos>-1)
                        {
                            fileDetailList.get(pos).Status=FileTransferStatus.Completed;
                            adapter.onOneItemChanged(this.listView,pos);
                            autoOpenFile(fileDetailList.get(pos));
                        }
                        break;
                    case FileEvent.CANCEL_TRANSFERING:
                        if(pos>-1)
                        {
                            fileDetailList.get(pos).Status=FileTransferStatus.Cancelled;
                            adapter.onOneItemChanged(this.listView,pos);
                        }
                        break;
                    case FileEvent.FILE_TRANS_DISRUPPTTED:
                        if(pos>-1)
                        {
                            fileDetailList.get(pos).Status=FileTransferStatus.Failed;
                            adapter.onOneItemChanged(this.listView,pos);
                            ToastUtils.showLong(GroupFileActivity.this,String.format("文件传输中断，原因：%s",event.Cause) );
                        }
                        break;
                    case FileEvent.FILE_PROCESS:
                        if(project.isProjectCancelled())
                        {
                            return;
                        }
                        if(pos>-1)
                        {
                            fileDetailList.get(pos).Status=FileTransferStatus.Transfering;
                            adapter.fileProcess(event);
//                            adapter.onOneItemChanged(this.listView,pos);
                        }
                    default:
                        break;
                }
            }
        }catch (Exception ex)
        {
            ex.printStackTrace();
            ToastUtils.showLong(GroupFileActivity.this,ex.getMessage());
        }
    }

    private int getFileDetailPos(String projectId) {
        for (int i = 0; i < fileDetailList.size(); i++) {
            FileDetail detail = fileDetailList.get(i);
            if (!StringHelper.isNullOrEmpty(detail.ProjectId) && detail.ProjectId.equals(projectId)) {
                return i;
            }
        }
        return -1;
    }

    /**
     * 自动打开文件   （图片，文本 会自动打开）
     * @param fileDetail
     * @return true:能自动打开；  false：未能自动打开
     */
    private boolean autoOpenFile(FileDetail fileDetail)
    {
        try {
            FileType type= FileHelper.getFileType(fileDetail.Name);
            if(type==FileType.Image)
            {
                BitmapFactory.Options options = new BitmapFactory.Options();
                /**
                 * 最关键在此，把options.inJustDecodeBounds = true;
                 * 这里再decodeFile()，返回的bitmap为空，但此时调用options.outHeight时，已经包含了图片的高了
                 */
                options.inJustDecodeBounds = true;
                BitmapFactory.decodeFile(fileDetail.SavePath,options);
                //photoView.set(options.outWidth,options.outHeight);

                findViewById(R.id.group1).setVisibility(View.GONE);
                Uri uri=Uri.parse(fileDetail.SavePath);
                photoView.setImageURI(uri);
                photoView.setVisibility(View.VISIBLE);
                return true;
            }else if(type==FileType.Txt)
            {

            }
        }catch (Exception e){e.printStackTrace();}
        return false;
    }


    public void finish(View view) {
        finish();
    }
}